package com.fantasy.Compared;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import com.fantasy.file.GetFolderAbsPath;
import com.fantasy.file.ReadTxt;
import com.fantasy.file.WriteTxt;
import com.fantasy.readproperties.ReadProperties;
import com.fantasy.string.StringUtils;

/**
 * author:Fantasy
 * 
 * Rmks:文件需要使用ANSI编码
 * */
public class ComparedTxt {

	private static String[] header;
	private static List<HashMap<String, String>> srcDataList;
	private static List<HashMap<String, String>> comDataList;
	private static String regex;
	
	private static String path = "Compared";
	
	public static HashMap<String , String > String2Map(String data){
		String[] datas = data.split(regex);
		int dataLength = header.length;
		HashMap<String, String> dataMap = new HashMap<String ,String>();
		for (int i = 0; i < dataLength ; i ++) {
			if(i >= datas.length){
				dataMap.put(header[i], "");
			}else{
				dataMap.put(header[i], datas[i]);
			}
		}
		return dataMap;
	}
	
	public static List<HashMap<String, String>> readTxt(String path){
		List<HashMap<String, String>> srcDataList2;
		//System.out.println("readTxt:" + path);
		srcDataList2 = new ArrayList<HashMap<String, String>>();
		BufferedReader bufReader = ReadTxt.GetBufferReader(path);
		String data;
		try {
			String headerString = bufReader.readLine();
			header = headerString.split(regex);
			//System.out.println("startTxt:" + headerString);
			data = bufReader.readLine();
			while(null != data){
				srcDataList2.add(String2Map(data));
				data = bufReader.readLine();
			}
			bufReader.close();
			//System.out.println( "datalength : " + dataLength + "srcDataListSize:" + dataList.size());
		} catch (IOException e) {
			try {
				bufReader.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
		
		return srcDataList2;
	}

	public static String[] calculateSign = {">","=","<","<>","endwith","startwith","equals","noequals","contains"};
	
	public static String[] formulaVar = {"A","B","C","D","E","F","G","H","I","J","K"};

	public static String getFileName(String fileName){
		fileName = fileName.substring(0 , fileName.lastIndexOf("."));
		return fileName;
	}
	
	/**
	 * 处理的文件过滤,过滤器
	 */
	private static FileFilter filter = new FileFilter() {
		public boolean accept(File pathname) {
			// 只处理：目录 或是 .java文件
			if (pathname.isDirectory()
					|| (pathname.isFile() && pathname.getName().endsWith(
							".txt"))) {
				return true;
			} else {
				return false;
			}
		}
	};
	
	public static void comparedList(List<HashMap<String, String>> srcDataList, List<HashMap<String, String>> comDataList, String[] compareField){
		List<CompareResEntity> resDataList = new ArrayList<CompareResEntity>();
		for (int srcInx = 0; srcInx < srcDataList.size() ;srcInx ++) {
			CompareResEntity resData = new CompareResEntity();
			HashMap<String, String> dataMap = srcDataList.get(srcInx);
			for(int comInx = 0 ; comInx < comDataList.size() ; comInx ++){
				HashMap<String, String> comDataMap = comDataList.get(comInx);
				CompareResEntity comData = comporeMap(dataMap , comDataMap , compareField);
				/**
				 * 找到相似度最高
				 * */
				if(comData.getCorrectNum() > resData.getCorrectNum() || resData.getCorrectNum() ==0){
					/*System.err.println(
							resData.toString() + 
							resData.getCorrectNum() + "," + resData.getEmptyCorrectNum());*/
					resData = comData;
					resData.setComInx(comInx);
					resData.setSrcInx(srcInx);
				}
			}
			//对比完成后对比结果
			if(resData.getCorrectNum() == 0){
				resData.setComInx(0);
				resData.setComRes("没有对应的compared对象");
			}
			resDataList.add(resData);
		}
		HashMap<String, String> lostSrcMap = new HashMap<>();
		boolean checkFlag = false;
		for(int checkInx = 0; checkInx < comDataList.size(); checkInx ++){
			//System.err.println(checkInx);
			checkFlag = false;
			for (CompareResEntity compareResEntity : resDataList) {
				if(checkInx == compareResEntity.getComInx()){
					checkFlag = true;
					if((compareResEntity.getEmptyCorrectNum() == compareResEntity.getCorrectNum() && compareResEntity.getCorrectNum() != 0)){
						if(!lostSrcMap.containsKey("" + checkInx) && compareResEntity.getCorrectNum() != compareField.length){
							System.out.println("++++++++" + checkInx);
							System.err.println(compareField.length + "+++" + compareResEntity.getCorrectNum() + "   " +
									compareResEntity.toString() + 
									compareResEntity.getCorrectNum() + "," + compareResEntity.getEmptyCorrectNum());
							lostSrcMap.put(checkInx + "", "true");
						}
					}
					break;
				}
			}
			if(!checkFlag){
				//完全在com里面找不到有相同字段。说明不是在src中找不到，而是没有对应的compare记录。
				//if(resDataList.get(checkInx).getCorrectNum() == 0){
					lostSrcMap.put(checkInx + "", "true");
				//}
			}
		}
		
		String resultPath = GetFolderAbsPath.getFolderPath(path) + "result.txt";
		WriteTxt.open(resultPath);
		WriteTxt.write("\r\n在compare文件中找不到\r\n|");
		for (int i = 0; i < compareField.length; i++) {
			WriteTxt.write(compareField[i] + "|");
		}
		WriteTxt.write("\r\n");
		for (CompareResEntity compareResEntity : resDataList) {
			if(compareResEntity.getCorrectNum() == 0 || 
					compareResEntity.getEmptyCorrectNum() == compareResEntity.getCorrectNum()){
				WriteTxt.write(compareResEntity.getSrcInx() + "|");
				for (int i = 0; i < compareField.length; i++) {
					WriteTxt.write(srcDataList.get(compareResEntity.getSrcInx()).get(compareField[i] ) + "|");
				}
				WriteTxt.write("\r\n");
			}
		}
		WriteTxt.write("\r\n在src文件中找不到\r\n|");
		for (int i = 0; i < compareField.length; i++) {
			WriteTxt.write(compareField[i] + "|");
		}
		WriteTxt.write("\r\n");
		for (Entry<String, String> lostSrc : lostSrcMap.entrySet()) {
			int comInx = Integer.valueOf(lostSrc.getKey());
			WriteTxt.write(lostSrc.getKey() + "|");
			for (int i = 0; i < compareField.length; i++) {
				WriteTxt.write(comDataList.get(comInx).get(compareField[i] ) + "|");
			}
			WriteTxt.write("\r\n");
		}
		WriteTxt.write("\r\nsrc文件与compare文件不同\r\nsrc|");
		for (int i = 0; i < compareField.length; i++) {
			WriteTxt.write(compareField[i] + "|");
		}
		WriteTxt.write("|com|");
		for (int i = 0; i < compareField.length; i++) {
			WriteTxt.write(compareField[i] + "|");
		}
		WriteTxt.write("\r\n");
		for (CompareResEntity compareResEntity : resDataList) {
			if(compareResEntity.getCorrectNum() != 0 && compareResEntity.getCorrectNum() != compareField.length && 
					compareResEntity.getEmptyCorrectNum() != compareResEntity.getCorrectNum()){
				for (int i = 0; i < compareField.length; i++) {
					WriteTxt.write(srcDataList.get(compareResEntity.getSrcInx() ).get(compareField[i] ) + "|");
				}
				WriteTxt.write("|com|");
				for (int i = 0; i < compareField.length; i++) {
					WriteTxt.write(comDataList.get(compareResEntity.getComInx() ).get(compareField[i] ) + "|");
				}
				WriteTxt.write("\r\n");
				
				//WriteTxt.write(compareResEntity.getCorrectNum() + "  com第" + (compareResEntity.getComInx() + 1) + "行,src第" + (compareResEntity.getSrcInx() + 1)
				//		+ "行:" + compareResEntity.getComRes() + "\r\n");
			}
		}
		WriteTxt.close();
	}
	
	public static CompareResEntity comporeMap(HashMap<String, String> srcMap , HashMap<String, String> comMap , String[] compareField){
		CompareResEntity resData = new CompareResEntity();
		int correctNum = 0;
		int emptyCorrectNum = 0;
		String resString = "";
		for (String string : compareField) {
			//System.out.println("compare:" + srcMap.get(string) +"****"+ comMap.get(string) + ",.,.,.," + StringUtils.contrastNoSensitive(srcMap.get(string), comMap.get(string)));
			if(StringUtils.contrastNoSensitive(srcMap.get(string), comMap.get(string))){
				correctNum = correctNum + 1;
				if(srcMap.get(string).length() == 0 ){
					emptyCorrectNum = emptyCorrectNum + 1;
				}
			}else{
				resString = resString + "|" + string + "===>src:" + srcMap.get(string) + "|com:" + comMap.get(string);
			}
		}
		resData.setCorrectNum(correctNum);
		resData.setEmptyCorrectNum(emptyCorrectNum);
		resData.setComRes(resString);
		return resData;
	}
	
	public static void main(String[] args) {
		//String path = "\\\\tsad\\Department\\MIS\\Current Data\\MIS2015\\Common\\MFG-Pro\\QAD-2015EE-Setup\\Setup\\Fantasy\\supplier";
		String srcPath = GetFolderAbsPath.getFolderPath("Compared");
		regex = ReadProperties.read("Compared.properties").getProperty("dataRegex").replace("|", "\\|");
		
		File srcF = new File(srcPath + "/source");
		File comF = new File(srcPath + "/compare");
		String[] compareField = ReadProperties.getProperty("Compared.properties" ,"compareFields").split(regex);
		for (File childF : srcF.listFiles(filter)) {
			String childFPath = childF.getAbsolutePath();
			srcDataList = readTxt(childFPath);
			if (compareField == null || compareField[0].length() == 0) {
				compareField = header;
			}
			comDataList = readTxt(new File(comF , childF.getName()).getAbsolutePath());
			comparedList(srcDataList, comDataList , compareField);
		}
	}
}
